﻿using System;
using System.Collections.Generic;
using System.Linq;
using Microsoft.AspNetCore.Mvc;
using IMS.Api.Repository;
using IMS.Api.Entity;
using Microsoft.Extensions.Configuration;
using IMS.Api.Utils;
using IMS.Api.ParamModel;
using Microsoft.AspNetCore.Authorization;

namespace IMS.Api.Controllers
{
    // 全局验证token
    [Authorize]
    [ApiController]
    [Route("[controller]")]
    public class CommoditiesController : ControllerBase
    {
        // 定义调用商品表的接口
        private IRepository<Commodities> _commoditiesRepository;
        // 定义调用店铺表的接口
        private IRepository<Stores> _storesRepository;
        // 定义调用商品类型表的接口
        private IRepository<CommodityTypes> _commodityTypesRepository;
        // 定义商铺表的接口
        private IRepository<Stores> _storesTypesRepository;
        // 定义token
        private TokenParameter _tokenParameter;
        // 定义配置访问接口
        private readonly IConfiguration _configuration;

        // 依赖注入
        public CommoditiesController(IConfiguration configuration, IRepository<Commodities> commoditiesRepository, IRepository<Stores> storesRepository, IRepository<CommodityTypes> commodityTypesRepository, IRepository<Stores> storesTypesRepository)
        {
            _configuration = configuration;
            _storesRepository = storesRepository;
            _commoditiesRepository = commoditiesRepository;
            _commodityTypesRepository = commodityTypesRepository;
            _storesTypesRepository = storesTypesRepository;
            // Token
            _tokenParameter =
                configuration
                    .GetSection("tokenParameter")
                    .Get<TokenParameter>();
        }

        // 跳过token验证
        [AllowAnonymous]
        // 获取商品表数据
        [HttpGet]
        public dynamic GetCommoditiesList([FromQuery] Pager pager)
        {
            // 页码（当前第几页）
            var pageIndex = pager.PageIndex;
            // 页大小（一页里面行的数量）
            var pageSize = pager.PageSize;
            // 查询的内容
            var query = pager.Query;
            // 查询的类型
            var queryType = pager.QueryType;
            // 判断是否查询
            if (string.IsNullOrEmpty(query))
            {
                var commodities = _commoditiesRepository.Table.ToList();
                // 判断商品表是否为空
                if (commodities != null)
                {
                    // 商品表不为空
                    // 判断是否进入回收站
                    var recycle = pager.Recycle;
                    if (recycle)
                    {
                        // 进入回收站
                        // 查看状态为删除商品表
                        var deletedCommodity = _commoditiesRepository.DeleteTable;
                        // 给状态为删除的商品表分页
                        var deletedTable = deletedCommodity.OrderByDescending(x => x.Id).Skip((pageIndex - 1) * pageSize).Take(pageSize).ToList();

                        return JsonHelper.Serialize(new
                        {
                            Data = new { DeletedCommodities = deletedTable, Pager = new { pageIndex, pageSize, PageTotal = deletedCommodity.Count() } },
                            Meta = new
                            {
                                Msg = "获取已删除商品列表成功！",
                                Status = 200
                            }
                        });
                    }
                    else
                    {
                        // 没有进入回收站
                        // 店铺表
                        var stores = _storesRepository.Table.ToList().OrderBy(x => x.Id);
                        // 商品表分页
                        var activedTable = commodities.OrderByDescending(x => x.Id).Skip((pageIndex - 1) * pageSize).Take(pageSize).ToList();

                        return JsonHelper.Serialize(new
                        {
                            Data = new { Commodities = activedTable, Stores = stores, Pager = new { pageIndex, pageSize, PageTotal = commodities.Count() } },
                            Meta = new
                            {
                                Msg = "获取商品列表成功！",
                                Status = 200
                            }
                        });
                    }
                }
                else
                {
                    // 商品表为空
                    return JsonHelper.Serialize(new
                    {
                        Data = "",
                        Meta = new
                        {
                            Msg = "商品列表获取异常！",
                            Status = 400
                        }
                    });
                }

            }
            else
            {
                // 判断查找类型（0--根据商品名称查找，1--根据商品类型查找，2--根据店铺名称查找）
                if (queryType == 0)
                {
                    // 根据商品名称查找
                    var commodities = _commoditiesRepository.Table.ToList().Where(x => x.CommodityName.Contains(query));
                    // 判断查询的商品名称是否为空
                    if (commodities != null)
                    {
                        // 查询的商品名称不为空
                        // 给查询到的内容分页
                        // var activedTable = commodities.Skip((pageIndex - 1) * pageSize).Take(pageSize).ToList();
                        return JsonHelper.Serialize(new
                        {
                            Data = new { Commodities = commodities },
                            Meta = new
                            {
                                Msg = "商品数据查询成功！",
                                Status = 200
                            }
                        });
                    }
                    else
                    {
                        // 查询的商品名称为空
                        return JsonHelper.Serialize(new
                        {
                            Data = "",
                            Meta = new
                            {
                                Msg = "没有找到你查询的商品名称！",
                                Status = 400
                            }
                        });
                    }
                }
                else if (queryType == 1)
                {
                    // 根据商品类型查找
                    var commodities = _commoditiesRepository.Table.ToList().Where(x => x.CommodityTypeName.Contains(query));
                    // 判断查询的商品类型是否为空
                    if (commodities != null)
                    {
                        // 查询商品类型不为空
                        // 给查询到的内容分页
                        var activedTable = commodities.Skip((pageIndex - 1) * pageSize).Take(pageSize).ToList();
                        return JsonHelper.Serialize(new
                        {
                            Data = new { Commodities = activedTable, Pager = new { pageIndex, pageSize, PageTotal = commodities.Count() } },
                            Meta = new
                            {
                                Msg = "商品数据查询成功！",
                                Status = 200
                            }
                        });
                    }
                    else
                    {
                        // 查询的商品类型为空
                        return JsonHelper.Serialize(new
                        {
                            Data = "",
                            Meta = new
                            {
                                Msg = "没有找到你查询的商品类型！",
                                Status = 400
                            }
                        });
                    }
                }
                else if (queryType == 2)
                {
                    // 根据店铺名称查找
                    var storeId = _storesTypesRepository.Table.ToList().Where(x => x.StoreName.Contains(query)).FirstOrDefault().Id;
                    // 对应店铺Id的商品
                    var commodities = _commoditiesRepository.Table.ToList().Where(x => x.FromStoreId == storeId);
                    // 判断查询的商铺是否为空
                    if (commodities != null)
                    {
                        // 查询的商铺不为空
                        // 给查询到的内容分页
                        var activedTable = commodities.Skip((pageIndex - 1) * pageSize).Take(pageSize).ToList();
                        return JsonHelper.Serialize(new
                        {
                            Data = new { Commodities = activedTable, Pager = new { pageIndex, pageSize, PageTotal = commodities.Count() } },
                            Meta = new
                            {
                                Msg = "商品数据查询成功！",
                                Status = 200
                            }
                        });
                    }
                    else
                    {
                        // 查询的商铺为空
                        return JsonHelper.Serialize(new
                        {
                            Data = "",
                            Meta = new
                            {
                                Msg = "没有找到你查询的商品！",
                                Status = 400
                            }
                        });
                    }
                }
                else
                {
                    // 查询的类型有误
                    return JsonHelper.Serialize(new
                    {
                        Data = "",
                        Meta = new
                        {
                            Msg = "你的查询请求类型有误！",
                            Status = 400
                        }
                    });
                }
            }
        }

        [HttpGet]
        // 根据所有商品
        [HttpGet, Route("all")]
        public dynamic GetAllCommodity()
        {
            var commodities = _commoditiesRepository.Table.ToList();
            if (commodities != null)
            {
                // 查询的商品列表不为空
                return JsonHelper.Serialize(new
                {
                    Data = commodities,
                    Meta = new
                    {
                        Msg = "获取商品列表成功！",
                        Status = 200
                    }
                });
            }
            else
            {
                // 查询的商品列表为空
                return JsonHelper.Serialize(new
                {
                    Data = "",
                    Meta = new
                    {
                        Msg = "获取商品列表为空！",
                        Status = 400
                    }
                });
            }

        }

        // // 跳过token验证
        // [AllowAnonymous]
        // // 根据排行榜请求获取商品
        // [HttpGet("ranking/{id}"), Route("ranking")]
        // public dynamic GetCommodity(int id)
        // {
        //     // 排行榜获取列表请求类型（1--阅读量排行2--点赞排行3--评论排行）
        //     if (id == 1)
        //     {
        //         // 阅读量排行
        //         var commoditiesViewsOrder = _commoditiesRepository.Table.ToList().OrderByDescending(x => x.CommodityViews).Take(10);
        //         if (commoditiesViewsOrder != null)
        //         {
        //             // 阅读量排行获取成功
        //             return JsonHelper.Serialize(new
        //             {
        //                 Data = commoditiesViewsOrder,
        //                 Meta = new
        //                 {
        //                     Msg = "阅读量排行榜数据获取成功！",
        //                     Status = 200
        //                 }
        //             });
        //         }
        //         else
        //         {
        //             // 阅读量排行获取失败
        //             return JsonHelper.Serialize(new
        //             {
        //                 Data = "",
        //                 Meta = new
        //                 {
        //                     Msg = "阅读量排行榜数据获取异常！",
        //                     Status = 400
        //                 }
        //             });
        //         }
        //     }
        //     else if (id == 2)
        //     {
        //         // 点赞排行
        //         var articlePraiseCountOrder = _commoditiesRepository.Table.ToList().OrderByDescending(x => x.CommodityPraiseCount).Take(10);
        //         if (articlePraiseCountOrder != null)
        //         {
        //             // 点赞排行获取成功
        //             return JsonHelper.Serialize(new
        //             {
        //                 Data = articlePraiseCountOrder,
        //                 Meta = new
        //                 {
        //                     Msg = "点赞排行榜数据获取成功！",
        //                     Status = 200
        //                 }
        //             });
        //         }
        //         else
        //         {
        //             // 点赞排行获取失败
        //             return JsonHelper.Serialize(new
        //             {
        //                 Data = "",
        //                 Meta = new
        //                 {
        //                     Msg = "点赞排行榜数据获取异常！",
        //                     Status = 400
        //                 }
        //             });
        //         }
        //     }
        //     else if (id == 3)
        //     {
        //         // 评论排行
        //         var articleCommentCountOrder = _commoditiesRepository.Table.ToList().OrderByDescending(x => x.CommodityCommentCount).Take(10);
        //         if (articleCommentCountOrder != null)
        //         {
        //             // 评论排行获取成功
        //             return JsonHelper.Serialize(new
        //             {
        //                 Data = articleCommentCountOrder,
        //                 Meta = new
        //                 {
        //                     Msg = "评论排行榜数据获取成功！",
        //                     Status = 200
        //                 }
        //             });
        //         }
        //         else
        //         {
        //             // 评论排行获取失败
        //             return JsonHelper.Serialize(new
        //             {
        //                 Data = "",
        //                 Meta = new
        //                 {
        //                     Msg = "评论排行榜数据获取异常！",
        //                     Status = 400
        //                 }
        //             });
        //         }
        //     }
        //     else
        //     {
        //         // 请求查询排行榜类型有误
        //         return JsonHelper.Serialize(new
        //         {
        //             Data = "",
        //             Meta = new
        //             {
        //                 Msg = "排行榜数据获取异常，请求类型有误！",
        //                 Status = 400
        //             }
        //         });
        //     }
        // }

        // 跳过token验证
        [AllowAnonymous]
        // 根据商品Id获取商品
        [HttpGet("id/{id}"), Route("id")]
        public dynamic GetCommodityById(int id)
        {
            var commodities = _commoditiesRepository.GetById(id);
            // var categoryId = _commodityTypesRepository.Table.Where(x => x.Id == commodities.CategoryId).ToList()[0].Id;
            // 判断传入的id是否在类型表存在
            if (commodities != null)
            {
                // 查询的Id的商品表存在
                return JsonHelper.Serialize(new
                {
                    Data = new { Commodities = commodities },
                    Meta = new
                    {
                        Msg = "商品数据获取成功！",
                        Status = 200
                    }
                });
            }
            else
            {
                // 查询的Id的商品表不存在
                return JsonHelper.Serialize(new
                {
                    Data = "",
                    Meta = new
                    {
                        Msg = "商品数据获取异常！",
                        Status = 400
                    }
                });
            }
        }

        // 添加新商品
        [HttpPost]
        public dynamic AddCommodity(NewCommodity model)
        {
            // 商品商铺Id
            var fromStoreId = model.FromStoreId;
            // 店铺名称
            var storeName = _storesRepository.Table.Where(x => x.Id == fromStoreId).ToList().FirstOrDefault().StoreName;
            // 商品图片Id
            var commodityImagesId = model.CommodityImagesId.ToString();
            // 商品类型Id
            var commodityTypeId = model.CommodityTypeId;
            // 截取字符串为数组
            string[] typeIds = commodityTypeId.Split(',');
            // 截取最后字符串最后一位
            var typeId = int.Parse(typeIds[typeIds.Length - 1]);
            // 商品类型名称
            var commodityTypeName = _commodityTypesRepository.Table.Where(x => x.Id == typeId).ToList().FirstOrDefault().CommodityTypeName;
            // 商品名称
            var commodityName = model.CommodityName;
            // 商品价格
            var commodityPrices = model.CommodityPrices;
            // 商品库存
            var commodityStocks = model.CommodityStocks;
            // 商品详情
            var commodityDetails = model.CommodityDetails;
            // // 商品规格
            // var commodityParamsId = model.CommodityParamsId;
            // 商品出售地址
            var commodityAddress = model.CommodityAddress;

            // 判断商品标题和商品内容是否为空
            // if (string.IsNullOrEmpty(commodityName) && string.IsNullOrEmpty(commodityParamsId))
            if (string.IsNullOrEmpty(commodityName))
            {
                // 商品标题和商品内容为空
                return JsonHelper.Serialize(new
                {
                    Data = "",
                    Meta = new
                    {
                        Msg = "插入的商品标题和内容不能为空，请确认后重试！",
                        Status = 400
                    }
                });
            }
            else
            {
                // 商品标题和商品内容不为空
                var commodities = new Commodities
                {
                    FromStoreId = fromStoreId,
                    CommodityImagesId = commodityImagesId,
                    CommodityTypeId = commodityTypeId,
                    CommodityName = commodityName,
                    StoreName = storeName,
                    CommodityTypeName = commodityTypeName,
                    CommodityPrices = commodityPrices,
                    CommodityStocks = commodityStocks,
                    CommodityDetails = commodityDetails,
                    // CommodityParamsId = commodityParamsId,
                    CommodityAddress = commodityAddress
                };
                // 插入商品
                _commoditiesRepository.Insert(commodities);

                // // 查询对应类型Id对应的类型数据
                // var commodityTypes = _commodityTypesRepository.GetById(categoryId);
                // // 更新一下类型表对应类型总数
                // var commoditiesCount = _commoditiesRepository.Table.ToList().Where(x => x.CategoryId == categoryId).Count();
                // // 类型商品总数
                // commodityTypes.CommoditiesCount = commoditiesCount;
                // // 更新类型表商品总数
                // _commodityTypesRepository.Update(commodityTypes);

                return JsonHelper.Serialize(new
                {
                    Data = commodities,
                    Meta = new
                    {
                        Msg = "创建成功！",
                        Status = 200
                    }
                });
            }
        }

        // 商品信息修改
        [HttpPut("{id}")]
        public dynamic ModCommodity(int id, NewCommodity model)
        {
            var commodities = _commoditiesRepository.GetById(id);
            // 判断所修改商品Id是否存在
            if (commodities != null)
            {
                // var oldCategoryId = commodities.CategoryId;
                // 要修改的商品Id存在
                // 店铺Id
                commodities.FromStoreId = model.FromStoreId;
                // 店铺名称
                commodities.StoreName = _storesRepository.Table.Where(x => x.Id == model.FromStoreId).ToList().FirstOrDefault().StoreName;
                // 商品图片Id
                commodities.CommodityImagesId = model.CommodityImagesId.ToString();
                // 商品类型Id
                commodities.CommodityTypeId = model.CommodityTypeId;
                // 截取字符串为数组
                string[] typeIds = model.CommodityTypeId.Split(',');
                // 截取最后字符串最后一位
                var typeId = int.Parse(typeIds[typeIds.Length - 1]);
                // 商品类型名称
                var commodityTypeName = _commodityTypesRepository.Table.Where(x => x.Id == typeId).ToList().FirstOrDefault().CommodityTypeName;
                // 商品类型名称
                commodities.CommodityTypeName = commodityTypeName;
                // 商品名称
                commodities.CommodityName = model.CommodityName;
                // 商品价格
                commodities.CommodityPrices = model.CommodityPrices;
                // 商品库存
                commodities.CommodityStocks = model.CommodityStocks;
                // 商品详情
                commodities.CommodityDetails = model.CommodityDetails;
                // 商品规格
                commodities.CommodityParamsId = model.CommodityParamsId;
                // 商品出售地址
                commodities.CommodityAddress = model.CommodityAddress;

                // 更新商品
                _commoditiesRepository.Update(commodities);

                // // 查询对应类型Id对应的类型数据
                // var oldCommodityTypes = _commodityTypesRepository.GetById(oldCategoryId);
                // // 更新一下类型表对应类型总数
                // var oldCommoditiesCount = _commoditiesRepository.Table.ToList().Where(x => x.CategoryId == oldCategoryId).Count();
                // // 类型商品总数
                // oldCommodityTypes.CommoditiesCount = oldCommoditiesCount;
                // // 更新类型表商品总数
                // _commodityTypesRepository.Update(oldCommodityTypes);

                // // 查询对应类型Id对应的类型数据
                // var commodityTypes = _commodityTypesRepository.GetById(model.CategoryId);
                // // 更新一下类型表对应类型总数
                // var commoditiesCount = _commoditiesRepository.Table.ToList().Where(x => x.CategoryId == model.CategoryId).Count();
                // // 类型商品总数
                // commodityTypes.CommoditiesCount = commoditiesCount;
                // // 更新类型表商品总数
                // _commodityTypesRepository.Update(commodityTypes);

                return JsonHelper.Serialize(new
                {
                    Data = commodities,
                    Meta = new
                    {
                        Msg = string.Format("你修改的商品的id为: {0} ，已经修改成功，请注意查收！", id),
                        Status = 200
                    }
                });
            }
            else
            {
                // 要修改的商品Id不存在
                return JsonHelper.Serialize(new
                {
                    Data = "",
                    Meta = new
                    {
                        Msg = "指定Id的商品不存在，请确认后重试！",
                        Status = 400
                    }
                });
            }
        }

        // 商品状态可用信息修改
        [HttpPut("status/{id}"), Route("status")]
        public dynamic ModStatus(int id)
        {
            var commodities = _commoditiesRepository.GetById(id);
            // 判断对应Id的商品是否存在
            if (commodities != null)
            {
                // 指定Id的商品存在
                _commoditiesRepository.ActiveStatus(id);
                return JsonHelper.Serialize(new
                {
                    Data = commodities,
                    Meta = new
                    {
                        Msg = string.Format("你修改的状态对应商品的id为: {0} ，已经修改成功，请注意查收！", id),
                        Status = 200
                    }
                });
            }
            else
            {
                // 指定Id的商品不存在
                return JsonHelper.Serialize(new
                {
                    Data = "",
                    Meta = new
                    {
                        Msg = "指定Id的商品不存在，请确认后重试！",
                        Status = 400
                    }
                });
            }
        }

        // 商品信息删除（伪删除）
        [HttpDelete("{id}")]
        public dynamic DeleteCommodity(int id)
        {
            var commodities = _commoditiesRepository.GetById(id);
            // 判断对应Id的商品是否存在
            if (commodities != null)
            {
                // 对应Id的商品存在
                // 伪删除操作
                _commoditiesRepository.PseudoDeletion(id);
                return JsonHelper.Serialize(new
                {
                    Data = commodities,
                    Meta = new
                    {
                        Msg = string.Format("你删除的商品Id为 {0} 的数据,删除成功！", id),
                        Status = 200
                    }
                });
            }
            else
            {
                // 对应Id的商品不存在
                return JsonHelper.Serialize(new
                {
                    Data = "",
                    Meta = new
                    {
                        Msg = string.Format("找不到的商品Id为 {0} 的数据,执行删除操作,", id),
                        Status = 400
                    }
                });
            }
        }

        // 商品信息删除（彻底删除）
        [HttpDelete("delete/{id}"), Route("delete")]
        public dynamic CompletelyDeleteCommodity(int id)
        {
            var commodities = _commoditiesRepository.GetById(id);
            // 判断对应Id的商品是否存在
            if (commodities != null)
            {
                // 指定Id的商品存在
                // 彻底删除
                _commoditiesRepository.Delete(id);
                return JsonHelper.Serialize(new
                {
                    Data = commodities,
                    Meta = new
                    {
                        Msg = string.Format("你删除的Id为 {0} 的数据,彻底删除成功！", id),
                        Status = 200
                    }
                });
            }
            else
            {
                // 指定Id的类型不存在
                return JsonHelper.Serialize(new
                {
                    Data = "",
                    Meta = new
                    {
                        Msg = string.Format("找不到的Id为 {0} 的数据,无法执行彻底删除操作,", id),
                        Status = 400
                    }
                });
            }
        }

        // 恢复被删除的商品数据
        [HttpDelete("recovery/{id}"), Route("recovery")]
        public dynamic RecoveryCommodity(int id)
        {
            var commodities = _commoditiesRepository.GetById(id);
            // 判断对应Id的商品是否存在
            if (commodities != null)
            {
                // 指定Id的商品存在
                // 恢复数据
                _commoditiesRepository.Recovery(id);
                return JsonHelper.Serialize(new
                {
                    Data = commodities,
                    Meta = new
                    {
                        Msg = string.Format("你恢复的商品的id为: {0} ，已经恢复成功，请注意查收！", id),
                        Status = 200
                    }

                });
            }
            else
            {
                // 指定Id的商品不存在
                return JsonHelper.Serialize(new
                {
                    Data = "",
                    Meta = new
                    {
                        Msg = "指定Id的商品不存在，恢复错误，请确认后重试！",
                        Status = 400
                    }
                });
            }
        }
    }
}
